package com.example.dev_demo.mybatis.generator;

import org.mybatis.generator.api.GeneratedXmlFile;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ExtendMapperXmlPlugin extends PluginAdapter {

    @Override
    public List<GeneratedXmlFile> contextGenerateAdditionalXmlFiles(IntrospectedTable introspectedTable) {
        // 生成扩展XML文件逻辑（保持不变）
        List<GeneratedXmlFile> files = new ArrayList<>();

        // 生成扩展Mapper XML文件
        String xmlFileName = introspectedTable.getMyBatis3XmlMapperFileName().replace(".xml", "_ext.xml");
        String xmlPackageName = introspectedTable.getMyBatis3XmlMapperPackage();
        String targetProject = context.getSqlMapGeneratorConfiguration().getTargetProject();

        if (!isFileExists(xmlFileName, xmlPackageName, targetProject)) {
            Document document = new Document("-//mybatis.org//DTD Mapper 3.0//EN",
                    "http://mybatis.org/dtd/mybatis-3-mapper.dtd");

            XmlElement root = new XmlElement("mapper");
            root.addAttribute(new Attribute("namespace",
                    introspectedTable.getMyBatis3JavaMapperType() + "Ext"));
            document.setRootElement(root);

//            // 添加自定义SQL元素
//            XmlElement select = new XmlElement("select");
//            select.addAttribute(new Attribute("id", "selectByCustomCondition"));
//            select.addAttribute(new Attribute("resultMap", "BaseResultMap"));
//            select.addAttribute(new Attribute("parameterType", "map"));
//            select.addElement(new TextElement("select * from " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
//            root.addElement(select);

            GeneratedXmlFile gxf = new GeneratedXmlFile(
                    document,
                    xmlFileName,
                    xmlPackageName,
                    targetProject,
                    false,
                    context.getXmlFormatter());

            files.add(gxf);
        }

        return files;
    }

//    @Override
//    public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable) {
//        // 生成扩展Mapper接口文件
//        String mapperType = introspectedTable.getMyBatis3JavaMapperType();
//        String extMapperType = mapperType.replace("Mapper","ExtMapper");
//
//        // 检查文件是否已存在
//        if (isJavaFileExists(extMapperType, context.getJavaClientGeneratorConfiguration().getTargetProject())) {
//            return Collections.emptyList();
//        }
//
//        // 创建扩展Mapper接口
//        Interface interfaze = new Interface(extMapperType);
//        interfaze.setVisibility(JavaVisibility.PUBLIC);
//
//        // 添加注释
//        interfaze.addJavaDocLine("/**");
//        interfaze.addJavaDocLine(" * " + introspectedTable.getFullyQualifiedTable().getIntrospectedTableName() + "表的扩展Mapper接口");
//        interfaze.addJavaDocLine(" */");
//
////        // 添加自定义方法
////        Method method = new Method("selectByCustomCondition");
////        method.setReturnType(new FullyQualifiedJavaType("java.util.List<" +
////                introspectedTable.getBaseRecordType() + ">"));
////        method.addParameter(new Parameter(new FullyQualifiedJavaType("java.util.Map"), "params"));
////        method.addJavaDocLine("/**");
////        method.addJavaDocLine(" * 根据自定义条件查询");
////        method.addJavaDocLine(" * @param params 查询参数");
////        method.addJavaDocLine(" * @return 查询结果列表");
////        method.addJavaDocLine(" */");
////        interfaze.addMethod(method);
//
//        // 设置包名
//        String targetPackage = introspectedTable.getContext().getJavaClientGeneratorConfiguration().getTargetPackage();
//
//        GeneratedJavaFile gjf = new GeneratedJavaFile(
//                interfaze,
//                context.getJavaClientGeneratorConfiguration().getTargetProject(),
//                context.getProperty("javaFileEncoding"),
//                context.getJavaFormatter());
//
//        return Collections.singletonList(gjf);
//    }
//
//    /**
//     * 检查Java文件是否已存在
//     */
//    private boolean isJavaFileExists(String fullTypeName, String targetProject) {
//        try {
//            DefaultShellCallback callback = new DefaultShellCallback(false);
//            String packageName = fullTypeName.substring(0, fullTypeName.lastIndexOf('.'));
//            String fileName = fullTypeName.substring(fullTypeName.lastIndexOf('.') + 1) + ".java";
//            File directory = callback.getDirectory(targetProject, packageName);
//            File targetFile = new File(directory, fileName);
//            return targetFile.exists();
//        } catch (Exception e) {
//            return false;
//        }
//    }

    /**
     * 检查XML文件是否已存在
     */
    private boolean isFileExists(String fileName, String packageName, String targetProject) {
        try {
            DefaultShellCallback callback = new DefaultShellCallback(false);
            File directory = callback.getDirectory(targetProject, packageName);
            File targetFile = new File(directory, fileName);
            return targetFile.exists();
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean validate(List<String> warnings) {
        return true;
    }
}